package projorientado.ocr.vfeature.impl;

import java.util.Iterator;
import projorientado.image.ImageComparatorProvider;
import projorientado.ocr.vfeature.FeaturesExtractor;
import projorientado.ocr.vfeature.FeaturesExtractorProvider;
import projorientado.ocr.vfeature.FeaturesPairExtractor;
import projorientado.ocr.vfeature.FeaturesPairExtractorProvider;
import projorientado.spi.ServiceProvider;
import projorientado.util.CodeTokenizer;
import projorientado.util.CodeTokenizer.CodeElement;
import projorientado.util.CodeTokenizer.CodeLine;
import projorientado.util.CodeTokenizer.CodeVarDef;

public class ImagePairExtractorProvider implements ServiceProvider<FeaturesPairExtractor> {

    private static final ImagePairExtractorProvider instance = new ImagePairExtractorProvider();
    
    static {
        FeaturesPairExtractorProvider.getInstance().registerServiceProvider("imagepairextractor", instance);
    }
    
    private ImagePairExtractorProvider() {
        
    }
    
    public static ImagePairExtractorProvider getInstance() {
        return instance;
    }
    
    public FeaturesPairExtractor getService(String s) {
        CodeTokenizer.CodeBlock root = CodeTokenizer.singleParse(s);
        
        FeaturesExtractor extractor = null;
        int sizeMode = 0;
        
        Iterator<CodeTokenizer.CodeElement> it = root.childs.iterator();
        while(it.hasNext()) {
            CodeElement e = it.next();
            if(e instanceof CodeTokenizer.CodeTextBlock) {
                CodeTokenizer.CodeTextBlock tblock = (CodeTokenizer.CodeTextBlock)e;
                String name = tblock.name.toLowerCase();
                
                if(name.startsWith("extractor:") || name.startsWith("featuresextractor:")) {
                    String service = tblock.name.substring(name.indexOf(':')+1);
                    extractor = FeaturesExtractorProvider.getFeaturesExtractor(service, tblock.text);
                }
            } else if(e instanceof CodeTokenizer.CodeLine) {
                CodeVarDef var = CodeTokenizer.parseVarDef(((CodeLine)e).line);
                if(var.varName.equalsIgnoreCase("sizemode") || var.varName.equalsIgnoreCase("size")) {
                    sizeMode = Integer.parseInt(var.value);
                }
            }
        }
        
        return new ImagePairExtractor(extractor,sizeMode);
    }

}
